package com.zhangfuyu.alibaba.service;


import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;


public class SumService implements Callable<Integer> {

    public static  final   CountDownLatch countDownLatch = new CountDownLatch(5);


    //省略 10000
    public static  List<Integer> num = new ArrayList<>();

    private List<Integer> sub = null;


    public SumService(List<Integer> s) {
        this.sub = s;
    }

    @Override
    public Integer call() {
        int sum = 0;
        for (Integer integer : this.sub) {
            sum= sum + integer;
        }
        countDownLatch.countDown();
        return sum;
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        int result = 0;
        for (int i = 1;i<=10000;i++){
            num.add(i);
        }

        ExecutorService executorService = Executors.newFixedThreadPool(5);
        List<Integer> sum = new ArrayList<>();
        int group = 10000/5;
        for (int i = 0;i<5;i++){
            SumService sumService = new SumService(SumService.num.subList((i*group),(group*i+group)));
            Future<Integer> submit = executorService.submit(sumService);
            Integer integer = submit.get();
            sum.add(integer);
        }
        countDownLatch.await();
        for (Integer integer : sum) {
            result = result+integer;
        }
        System.out.println("结果为："+ result);

    }
}
